﻿using EFCore.BulkExtensions;
using Furion.CMS.Core;
using Furion.CMS.Domain;
using Furion.DatabaseAccessor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.Application.Jobs
{
    /// <summary>
    /// 定时任务日志清理
    /// <para>
    /// 清理截止于上周天的数据
    /// </para>
    /// </summary>
    public class CrontabExecuteLogsClearJob : ICrontabDefinition
    {
        private string _ExecuteResult = "";
        public string DisplayName => "清理定时任务日志";

        public void Execute()
        {
            var recordRepository = App.GetService<IRepository<CrontabExecuteRecord>>();
            var clearEndDate = DateTime.Now.Date.AddDays(1 - Convert.ToInt16(DateTime.Now.DayOfWeek));
            var deleteCount = recordRepository.DetachedEntities.Where(t => t.CreatedTime < clearEndDate).BatchDelete();
            _ExecuteResult = $"本次清理了 {deleteCount} 条日志数据";
        }

        public string GetResult() => _ExecuteResult;
    }
}
